package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.*;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.MeasureType;

import javax.script.ScriptException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@BusinessDataConverter(
    auto = false,
    insertSql = "INSERT INTO ND_BPM_COUNTER_GUARANTEE\n" +
        "(ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, " +
        "MEASURE_TYPE, IS_FIX, FIX_TIME, ESTIMATE_VALUE, MEASURE_EXPLAIN, CHANGE_SIGN, IS_EFFECT, EXPIRE_TIME, FIX_EXPLAIN, " +
        "PROJECT_ID, REPLACE_NEWSTEP, MEASURE_DETAILS_ID, REVIEW_SIGN, TASK_ID, PROC_ID, TASK_DEF_KEY, SOURCE_ID, " +
        "FAX, ADDRESS, PROPERTY_CONTENT, CONTRACT_ID, PHONE, REVOCATION_TIME)\n" +
        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    updateSql = "UPDATE ND_BPM_COUNTER_GUARANTEE\n" +
        "SET CREATE_NAME=?, CREATE_BY=?, CREATE_DATE=?, UPDATE_NAME=?, UPDATE_BY=?, UPDATE_DATE=?, SYS_ORG_CODE=?, SYS_COMPANY_CODE=?, BPM_STATUS=?, MEASURE_TYPE=?, IS_FIX=?, FIX_TIME=?, ESTIMATE_VALUE=?, MEASURE_EXPLAIN=?, CHANGE_SIGN=?, IS_EFFECT=?, EXPIRE_TIME=?, FIX_EXPLAIN=?, PROJECT_ID=?, REPLACE_NEWSTEP=?, MEASURE_DETAILS_ID=?, REVIEW_SIGN=?, TASK_ID=?, PROC_ID=?, TASK_DEF_KEY=?, SOURCE_ID=?, FAX=?, ADDRESS=?, PROPERTY_CONTENT=?, CONTRACT_ID=?, PHONE=?, REVOCATION_TIME=?\n" +
        "WHERE ID = ?",
    findMigratedIdListSql = "SELECT ID FROM ND_BPM_COUNTER_GUARANTEE WHERE PROC_ID = ?"
)
public class NdBpmCounterGuarantee extends AbstractWorkflowBusiness {
  private boolean forPrefixDatum = false;

  public NdBpmCounterGuarantee(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId, String procInstId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
  }

  public NdBpmCounterGuarantee(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData,
                               ProgramArgument programArgument, String projectId, String procInstId, boolean forPrefixDatum) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
    this.forPrefixDatum = forPrefixDatum;
  }

  @Override
  public void migrate() throws Exception {

    // 查询老系统反担保措施列表(组成：原反担保措施+本次流程被撤销的反担保措施+本次流程新增措施，其中本次流程撤销和新增的措施在表btItemAskExhgSecurity中)
    List<Map> btItemAssureSecurityList =null;

    if(!this.forPrefixDatum) {
      btItemAssureSecurityList = this.sourceData.getBtItemAskExhgSecurityList().stream()
        .filter(btItemAssureSecurity->{
          if(btItemAssureSecurity.get("WORKFLOWNO").toString().equals(this.procInstId)){
            return  true;
          }
          return false;
        })
        .collect(Collectors.toList());
    } else {
        btItemAssureSecurityList = this.sourceData.getBtItemAssureSecurityList().stream()
              .filter(btItemAssureSecurity->{
                // 原反担保措施 and 新增担保措施
                if(btItemAssureSecurity.get("REPLACEFLAG").toString().equals("1") || btItemAssureSecurity.get("REPLACEFLAG").toString().equals("2")){
                  return true;
                }
                return false;
              })
              .collect(Collectors.toList());
    }

    for(Map.Entry<String,Map<String,Object>> entry : taskParamMap.entrySet()) {
      String curJbpmTaskInstanceId = entry.getKey();
      Map<String,Object> taskParam = entry.getValue();

      for (Map row : btItemAssureSecurityList) {
        try {
          // 判断是否需要覆盖迁移
          int needMigratedResult = this.needMigrated(row.get("DATUMNO").toString() + curJbpmTaskInstanceId);
          if(needMigratedResult == 0) {
            continue;
          }

          // 单条插入或更新
          if(needMigratedResult == 1) {
            this.targetDbUtil.updateByParams(updateSql,this.buildValues(row,curJbpmTaskInstanceId,taskParam),true);
          } else {
            this.targetDbUtil.updateByParams(insertSql,this.buildValues(row,curJbpmTaskInstanceId,taskParam));
          }
        } catch(Exception e) {
          throw new Exception(String.format("流程实例[%s]-任务实例[%s]-更替换反担保措施迁移失败:%s\n",this.procInstId, curJbpmTaskInstanceId, e.getMessage()));
        }
      }
    }

  }

  public List buildValues(Map row, String curJbpmTaskInstanceId, Map<String,Object> taskParam) throws ScriptException, SQLException {

    List values = new ArrayList();
    // ID
    values.add(row.get("DATUMNO").toString()+ curJbpmTaskInstanceId);
    // CREATE_NAME
    values.add(null);
    // CREATE_BY
    values.add(null);
    // CREATE_DATE
    values.add(row.get("CREATE_TIME"));
    // UPDATE_NAME
    values.add(null);
    // UPDATE_BY
    values.add(null);
    // UPDATE_DATE
    values.add(row.get("MODIFY_TIME"));
    // SYS_ORG_CODE
    values.add(null);
    // SYS_COMPANY_CODE
    values.add("002");
    // BPM_STATUS
    values.add(1);

    //  MEASURE_TYPE	措施类别
    String wayType = row.get("WAYTYPE").toString();
    String oldDictName = BusinessTool.getOldDictDataNameByDictCodeAndDataCode("24", wayType);
    String measureType = "";
    // 如果包含-,则是二级分类
    if(oldDictName.contains("-")){
      String[] dictNameArray = oldDictName.split("-");
      measureType = DictTool.getTargetDictCode(MeasureType.class,dictNameArray[0]);
    }else{
      measureType = DictTool.getTargetDictCode(MeasureType.class,oldDictName);
    }
    values.add(measureType);
    //  IS_FIX	12	VARCHAR2(32)	[NULL]	false	[NULL]	是否落实（旧系统：1-已落实，2-未落实），todo 新系统暂未确认
    values.add(row.get("ISTRANSACT"));
    //  FIX_TIME	13	DATE	[NULL]	false	[NULL]	落实时间
    values.add(row.get("VAILABLETIME"));
    //  ESTIMATE_VALUE	14	NUMBER(30,10)	[NULL]	false	[NULL]	评估价值
    values.add(row.get("PRICESUM"));
    //  MEASURE_EXPLAIN	15	VARCHAR2(2000)	[NULL]	false	[NULL]	措施说明
    values.add(Tool.decodeUnicode(row.get("TRANSACTMEMO")));
    //  CHANGE_SIGN	16	VARCHAR2(32)	[NULL]	false	[NULL]	置换标记（旧系统1：原反担保措施 2：被替换失效 3：新增替换措施）新系统（1：原反担保措施 ，2：被替换失效 ，3:新增替换措施 ，4：被撤消失效 ）
    values.add(row.get("REPLACEFLAG").toString().equals("4") ? "3" : row.get("REPLACEFLAG"));
    //  IS_EFFECT	17	VARCHAR2(32)	[NULL]	false	[NULL]	是否失效
    if(this.forPrefixDatum) {
//      values.add("not_expired");
    values.add("2".equals(row.get("OVERTIMEFLAG").toString()) ? "not_expired" : "expired");
    } else {
      if(row.get("REPLACEFLAG").toString().equals("2")) {
        values.add("expired");
      } else {
        values.add("not_expired");
      }
//      values.add("2".equals(row.get("OVERTIMEFLAG").toString()) ? "not_expired" : "expired");
    }
    //  EXPIRE_TIME	18	DATE	[NULL]	false	[NULL]	到期时间
    values.add(row.get("OVERTIME"));
    //  FIX_EXPLAIN	19	VARCHAR2(255)	[NULL]	false	[NULL]	落实情况说明
    values.add(null);
    //  PROJECT_ID	20	VARCHAR2(36)	[NULL]	false	[NULL]	项目ID
    values.add(this.projectId);
    //  REPLACE_NEWSTEP	21	VARCHAR2(32)	[NULL]	false	[NULL]	反担保置换取消新增标记 1：原反担保措施 => null,2：被替换失效 => replace,3：新增替换措施 => newstep
    values.add(getReplaceNewstep(row.get("REPLACEFLAG").toString()));
    //  MEASURE_DETAILS_ID	22	VARCHAR2(36)	[NULL]	false	[NULL]	反担保措施详细信息表ID
    values.add(row.get("DATUMNO")+ "-JW");
    //  REVIEW_SIGN	23	VARCHAR2(36)	[NULL]	false	[NULL]	审核标志
    if(this.forPrefixDatum) {
      values.add("1");
    } else {
      values.add("1");
//      values.add(Tool.isEmpty(row.get("AUDITFLAG")) ? null : ("1".equals(row.get("AUDITFLAG").toString()) ? "0":"1"));
    }
    //  TASK_ID	24	VARCHAR2(36)	[NULL]	false	[NULL]	任务ID
    values.add(curJbpmTaskInstanceId + "-JW");
    //  PROC_ID	25	VARCHAR2(36)	[NULL]	false	[NULL]	流程ID
    //values.add(Tool.isEmpty(btItemChargeAudit.get("AUDITWORKFLOWNO"))? null : btItemChargeAudit.get("AUDITWORKFLOWNO").toString() + "-JW");
    values.add(this.procInstId + "-JW");
    //  TASK_DEF_KEY	26	VARCHAR2(36)	[NULL]	false	[NULL]	节点ID
    values.add(taskParam.get("taskDefKey"));
    //  SOURCE_ID	27	VARCHAR2(36)	[NULL]	false	[NULL]	业务ID
    values.add(row.get("DATUMNO"));
    //  FAX	28	VARCHAR2(36)	[NULL]	false	[NULL]	传真
    values.add(null);
    //  ADDRESS	29	VARCHAR2(200)	[NULL]	false	[NULL]	住所
    values.add(row.get("OWNERADDRESS"));
    //  PROPERTY_CONTENT	30	VARCHAR2(2000)	[NULL]	false	[NULL]	财产内容
    values.add(null);
    //  CONTRACT_ID	31	VARCHAR2(36)	[NULL]	false	[NULL]	合同对应ID
    values.add(null);
    //  PHONE	32	VARCHAR2(36)	[NULL]	false	[NULL]	电话
    values.add(row.get("LINKTEL"));
    //  REVOCATION_TIME	33	DATE	[NULL]	false	[NULL]	撤销时间
    values.add(null);
    return values;
  }

  public String getReplaceNewstep(String replaceFlag) {
    if(replaceFlag.equals("2")){
      return "replace";
    }else if(replaceFlag.equals("3")) {
      return "newstep";
    }else if(replaceFlag.equals("4")) {
      return "replace";
    }
    return null;
  }

}
